package com.hd.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.hd.utils.RequestUtils;

public class CookieFilter implements Filter {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void destroy() {

	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;


		String currentURL = request.getRequestURI();

		int index = currentURL.indexOf("/", 1);
		String targetURL = "";

		if (index != -1) {
			targetURL = currentURL.substring(index, currentURL.length());
		} else {
			targetURL = currentURL;
		}
		
		if("/member_login.action".equals(targetURL)){
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}

		Cookie cookieLoginName = RequestUtils.getCookie(request, "loginName");

		Cookie cookiePassword = RequestUtils.getCookie(request, "password");

		Cookie cookieUserInfo = RequestUtils.getCookie(request, "userInfo");

		if (cookieLoginName != null && cookiePassword != null
				&& cookieUserInfo != null) {
			if (!StringUtils.isEmpty(cookieLoginName.getValue())
					&& !StringUtils.isEmpty(cookiePassword.getValue())
					&& !StringUtils.isEmpty(cookieUserInfo.getValue())) {
				if (cookieUserInfo.getValue().equals(
						cookieLoginName.getValue() + "_"
								+ cookiePassword.getValue())) {
					System.out.println("验证成功!");
				}
			}
		} else {
			System.out.println("非法访问");

				// 删除cookie
				RequestUtils.removeCookie(response, "loginName");
				RequestUtils.removeCookie(response, "password");
				RequestUtils.removeCookie(response, "userName");
	
				response.sendRedirect(request.getContextPath() + "/member_login.action");

		}
		filterChain.doFilter(servletRequest, servletResponse);
	}
}
